package com.mornd.controller.crud;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mornd.annotation.LogStar;
import com.mornd.consts.UserConst;
import com.mornd.entity.Menu;
import com.mornd.entity.TreeNode;
import com.mornd.result.AjaxResult;
import com.mornd.result.DataGridView;
import com.mornd.service.MenuService;
import com.mornd.vo.MenuVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author mornd
 * @date 2021/1/7 - 1:01
 */
@RestController
@RequestMapping("/menu")
@RequiresPermissions({"m:menu"})
public class MenuController {
    @Resource
    private MenuService menuService;

    /**
     * 查询菜单列表
     * @return
     */
    @LogStar("查询菜单")
    @RequestMapping("/findMenu")
    public DataGridView findMenu(MenuVo menuVo){
        IPage<Menu> list = menuService.findList(menuVo);
        return new DataGridView<Menu>(list.getTotal(),list.getRecords());
    }

    /**
     * 菜单页面加载左侧菜单树
     * @return
     */
    @RequestMapping("/loadMenuTree")
    public DataGridView initMenuTree(){
        List<Menu> simpleMenus = menuService.getSimpleMenus();
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        simpleMenus.forEach((menu)->{
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),
                    menu.getTitle(), menu.getSpread() == 1));
        });
        return new DataGridView((long) treeNodes.size(), treeNodes);
    }

    /**
     * 保存菜单
     * @param menu
     * @return
     */
    @LogStar("保存菜单")
    @PostMapping("/save")
    public Map saveMenu(Menu menu){
        if(ObjectUtils.isEmpty(menu) || ObjectUtils.isEmpty(menu.getPid())){
            return AjaxResult.failure("数据为空");
        }
        if(ObjectUtils.isEmpty(menu.getTitle()) || ObjectUtils.isEmpty(menu.getCode())){
            return AjaxResult.failure("请填写必填项");
        }
        //判断编码是不是以m:开头
        if(!menu.getCode().startsWith("m:") || "m:".equals(menu.getCode())){
            return AjaxResult.failure("编码格式不正确");
        }
        //判断菜单信息是否已经存在
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("title",menu.getTitle());
        if(!ObjectUtils.isEmpty(menuService.getOne(wrapper))){
            return AjaxResult.failure("该菜单名称已存在");
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("code",menu.getCode());
        if(!ObjectUtils.isEmpty(menuService.getOne(wrapper))){
            return AjaxResult.failure("该菜单编码已存在");
        }
        //如果菜单等级为0，则type为0，否则为1
        if(menu.getPid() == 0){
            menu.setType(0);
        }else{
            menu.setType(1);
        }
        //1为展开状态，0为折叠状态
        if(!ObjectUtils.isEmpty(menu.getSpread())){
            if(menu.getSpread() != 1) menu.setSpread(0);
        }
        if(menuService.save(menu)){
            //超级管理员自动添加全部菜单权限
            menuService.addMenuBySuperA(UserConst.SA_ID,menu.getId());
            return AjaxResult.success("保存菜单成功！");
        }
        return AjaxResult.failure("保存菜单失败，请重试！");
    }

    /**
     * 编辑菜单
     * @param menu
     * @return
     */
    @LogStar("编辑菜单")
    @PostMapping("/edit")
    public Map editMenu(Menu menu){
        if(ObjectUtils.isEmpty(menu)){
            return AjaxResult.failure("数据为空");
        }
        if(ObjectUtils.isEmpty(menu.getTitle()) || ObjectUtils.isEmpty(menu.getCode())){
            return AjaxResult.failure("请填写必填项");
        }
        //判断编码是不是以m:开头
        if(!menu.getCode().startsWith("m:") || "m:".equals(menu.getCode())){
            return AjaxResult.failure("编码格式不正确");
        }
        //判断菜单信息是否已经存在
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("title",menu.getTitle());
        Menu selectOne = menuService.getOne(wrapper);
        if(!ObjectUtils.isEmpty(selectOne) && !selectOne.getId().equals(menu.getId())){
            return AjaxResult.failure("该菜单名称已存在");
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("code",menu.getCode());
        selectOne = menuService.getOne(wrapper);
        if(!ObjectUtils.isEmpty(selectOne) && !selectOne.getId().equals(menu.getId())){
            return AjaxResult.failure("该菜单编码已存在");
        }
        //如果菜单等级为0，则type为0，否则为1
        if(menu.getPid() == 0){
            menu.setType(0);
        }else{
            menu.setType(1);
        }
        //1为展开状态，0为折叠状态
        if(!ObjectUtils.isEmpty(menu.getSpread())){
            if(menu.getSpread() != 1) menu.setSpread(0);
        }
        menu.setGmtModified(new Date());
        if(menuService.updateById(menu)){
            return AjaxResult.success("菜单修改成功！");
        }
        return AjaxResult.failure("菜单修改失败，请重试！");
    }


    /**
     * 检查该菜单下是否有子菜单
     * @param menuId
     * @return
     */
    @PostMapping("/checkHasChildrenNode/{id}")
    public Map checkHasChildrenNode(@PathVariable("id") Integer menuId){
        AjaxResult result = new AjaxResult();
        if(menuService.checkHasChildrenNode(menuId) > 0){
            return AjaxResult.isExists(true,"请先删除子菜单！");
        }
        return AjaxResult.isExists(false,null);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @LogStar("删除菜单")
    @PostMapping("/delete/{menuId}")
    public Map deleteMenu(@PathVariable("menuId") Integer id){
        if(menuService.removeById(id)){
            return AjaxResult.success("删除菜单成功！");
        }
        return AjaxResult.failure("删除菜单失败，请重试！");
    }
}
